package logic

import (
	"context"

	model "paper-pro/app/assistant/model/assistant"
	"paper-pro/app/assistant/rpc/internal/svc"
	"paper-pro/app/assistant/rpc/pb"
	"paper-pro/pkg/xerr"

	"github.com/jinzhu/copier"
	"github.com/pkg/errors"
	"github.com/zeromicro/go-zero/core/logx"
)

var ErrAssistantNoExistsError = xerr.NewErrMsg("助理不存在")
var ErrAssistantPermissionDenied = xerr.NewErrMsg("没有该助理权限")

type GetAssistantLogic struct {
	ctx    context.Context
	svcCtx *svc.ServiceContext
	logx.Logger
}

func NewGetAssistantLogic(ctx context.Context, svcCtx *svc.ServiceContext) *GetAssistantLogic {
	return &GetAssistantLogic{
		ctx:    ctx,
		svcCtx: svcCtx,
		Logger: logx.WithContext(ctx),
	}
}

func (l *GetAssistantLogic) GetAssistant(in *pb.GetAssistantReq) (*pb.GetAssistantResp, error) {
	assistant, err := l.svcCtx.AssistantModel.FindOne(l.ctx, in.Id, in.UserId)
	if err != nil && err != model.ErrNotFound {
		return nil, errors.Wrapf(xerr.NewErrCode(xerr.DB_ERROR),
			"获取ID: %s Assistant信息失败，err: %v", in.Id, err)
	}
	if assistant == nil {
		return nil, errors.Wrapf(ErrAssistantNoExistsError, "GetAssistants ID:%s", in.Id)
	}
	if assistant.UserId != in.UserId {
		return nil, errors.Wrapf(ErrAssistantPermissionDenied,
			"GetAssistant ID: %s failed, belong User: %d, op User: %d", in.Id, assistant.UserId, in.UserId)
	}

	var assistantInfo pb.AssistantInfo
	err = copier.CopyWithOption(&assistantInfo, assistant, copier.Option{DeepCopy: true})
	if err != nil {
		return nil, errors.Wrap(err, "GetAssistant数据转换失败")
	}
	assistantInfo.Id = assistant.ID.Hex()
	assistantInfo.CreateAt = assistant.CreateAt.Unix()
	assistantInfo.UpdateAt = assistant.UpdateAt.Unix()

	return &pb.GetAssistantResp{
		AssistantInfo: &assistantInfo,
	}, nil
}
